package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.CustomerException;
import com.example.dao.setmealDao;
import com.example.domain.Setmeal;
import com.example.domain.SetmealDish;
import com.example.dto.SetmealDto;
import com.example.service.SetmealDishService;
import com.example.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<setmealDao, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    @Transactional
    public void saveWithDishes(SetmealDto setmealDto) {

        this.save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        setmealDishes.stream().map(setmealDish -> {

        setmealDish.setSetmealId(setmealDto.getId());

        return setmealDish;

    }).collect(Collectors.toList());

        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    public SetmealDto getWithDish(Long id) {

        Setmeal byId = this.getById(id);

        SetmealDto setmealDto = new SetmealDto();

        BeanUtils.copyProperties(byId, setmealDto);

        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<SetmealDish>();

        wrapper.eq(SetmealDish::getSetmealId, id);

        List<SetmealDish> list = setmealDishService.list(wrapper);

        setmealDto.setSetmealDishes(list);

        return setmealDto;

    }

    @Override
    @Transactional
    public void removeWithDishes(List<Long> ids) {

        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<Setmeal>();

        wrapper.in(Setmeal::getId,ids);

        wrapper.eq(Setmeal::getStatus,1);

        int count = this.count(wrapper);

        if(count>0){

            throw new CustomerException("该套餐正在售卖，不能删除");
        }


        this.removeByIds(ids);

        setmealDishService.remove(new LambdaQueryWrapper<SetmealDish>().in(SetmealDish::getSetmealId,ids));


    }

    @Override
    public void changeStatus(Integer status, List<Long> ids) {

        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<Setmeal>();

        wrapper.in(Setmeal::getId,ids);

        List<Setmeal> list = this.list(wrapper);

        list = list.stream().map(setmeal -> {
            setmeal.setStatus(status);
            return setmeal;
        }).collect(Collectors.toList());

        this.updateBatchById(list);
    }

}
